package dissertation.extensions.generate.ejb.view;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.ClassUtil;
import com.intellij.ui.DocumentAdapter;
import dissertation.services.ejbclass.EJBClassService;
import dissertation.services.ejbclass.IEJBClassService;

import javax.swing.*;
import javax.swing.event.DocumentEvent;

public class CreateEJBDialogWrapper extends DialogWrapper {
    private CreateEJBPanel createEJBPanel;
    private Project project;
    private IEJBClassService ejbClassService;

    public CreateEJBDialogWrapper(Project project) {
        super(project);
        init();
        setResizable(false);
        setOKActionEnabled(false);
        this.project = project;
        ejbClassService = new EJBClassService();
    }

    @Override
    protected JComponent createCenterPanel() {
        DocumentAdapter documentAdapter = new DocumentAdapter() {
            protected void textChanged(DocumentEvent e) {
                setOKActionEnabled(!createEJBPanel.getInputJTextField().getText().isEmpty());
            }
        };

        createEJBPanel = new CreateEJBPanel(documentAdapter);
        return createEJBPanel;
    }

    protected void doOKAction() {
        final PsiManager manager = PsiManager.getInstance(project);
        PsiClass aClass = ClassUtil.findPsiClass(manager, getInput());
        boolean foundAnnotation = ejbClassService.isEJBClass(aClass);

        if (!foundAnnotation) {
            Messages.showWarningDialog("The selected class is not an EJB Bean.", "Invalid EJB Bean");
        } else {
            close(OK_EXIT_CODE);
        }
    }

    public String getInput() {
        return createEJBPanel.getInputJTextField().getText();
    }
}
